// 云函数：试题批量导入
const cloud = require('wx-server-sdk');
const xlsx = require('node-xlsx');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const questionCollection = db.collection('questions');
const _ = db.command;

/**
 * Excel试题导入云函数
 * 
 * 参数：
 * - fileID: Excel文件云存储ID
 * 
 * Excel格式要求：
 * - 第一行为表头
 * - 必须包含列：题型、学科、题干、选项A、选项B、选项C、选项D、答案、解析、难度、知识点
 */
exports.main = async (event, context) => {
  const { fileID } = event;
  const wxContext = cloud.getWXContext();
  const userId = wxContext.OPENID;
  
  try {
    // 1. 下载Excel文件
    const fileResult = await cloud.downloadFile({
      fileID
    });
    const buffer = fileResult.fileContent;
    
    // 2. 解析Excel文件
    const sheets = xlsx.parse(buffer);
    
    // 默认使用第一个工作表
    if (!sheets || sheets.length === 0 || !sheets[0].data || sheets[0].data.length <= 1) {
      return {
        success: false,
        message: '无效的Excel文件或文件为空'
      };
    }
    
    const sheet = sheets[0];
    const rows = sheet.data;
    
    // 3. 获取表头和映射关系
    const headers = rows[0];
    const requiredColumns = ['题型', '学科', '题干', '答案', '难度'];
    
    // 检查必要列是否存在
    for (const col of requiredColumns) {
      if (!headers.includes(col)) {
        return {
          success: false,
          message: `Excel表格缺少必要列：${col}`
        };
      }
    }
    
    // 映射表头索引
    const columnMap = {
      type: headers.indexOf('题型'),
      subject: headers.indexOf('学科'),
      stem: headers.indexOf('题干'),
      optionA: headers.indexOf('选项A'),
      optionB: headers.indexOf('选项B'),
      optionC: headers.indexOf('选项C'),
      optionD: headers.indexOf('选项D'),
      answer: headers.indexOf('答案'),
      analysis: headers.indexOf('解析'),
      difficulty: headers.indexOf('难度'),
      knowledge: headers.indexOf('知识点')
    };
    
    // 4. 处理数据
    const questions = [];
    const failList = [];
    
    for (let i = 1; i < rows.length; i++) {
      const row = rows[i];
      
      // 跳过空行
      if (!row || row.length === 0 || !row[columnMap.stem]) {
        continue;
      }
      
      try {
        // 题型转换
        let questionType;
        const typeText = row[columnMap.type];
        
        switch (typeText) {
          case '单选题':
            questionType = 'single_choice';
            break;
          case '多选题':
            questionType = 'multiple_choice';
            break;
          case '判断题':
            questionType = 'true_false';
            break;
          case '填空题':
            questionType = 'fill_blank';
            break;
          case '简答题':
            questionType = 'short_answer';
            break;
          default:
            questionType = 'single_choice';
        }
        
        // 难度转换
        let difficulty;
        const difficultyText = row[columnMap.difficulty];
        
        if (/^[1-5]$/.test(difficultyText)) {
          difficulty = parseInt(difficultyText);
        } else if (/简单|容易/.test(difficultyText)) {
          difficulty = 1;
        } else if (/中等/.test(difficultyText)) {
          difficulty = 3;
        } else if (/困难|难/.test(difficultyText)) {
          difficulty = 5;
        } else {
          difficulty = 3; // 默认中等难度
        }
        
        // 知识点处理
        let knowledge = [];
        if (columnMap.knowledge >= 0 && row[columnMap.knowledge]) {
          knowledge = row[columnMap.knowledge].split(/[,，;；、]/);
        }
        
        // 选项处理
        const options = [];
        if (questionType === 'single_choice' || questionType === 'multiple_choice') {
          if (columnMap.optionA >= 0 && row[columnMap.optionA]) options.push(row[columnMap.optionA]);
          if (columnMap.optionB >= 0 && row[columnMap.optionB]) options.push(row[columnMap.optionB]);
          if (columnMap.optionC >= 0 && row[columnMap.optionC]) options.push(row[columnMap.optionC]);
          if (columnMap.optionD >= 0 && row[columnMap.optionD]) options.push(row[columnMap.optionD]);
        }
        
        // 创建试题对象
        const question = {
          type: questionType,
          subject: row[columnMap.subject],
          knowledge: knowledge,
          difficulty: difficulty,
          content: {
            stem: row[columnMap.stem],
            options: options,
            answer: row[columnMap.answer],
            analysis: columnMap.analysis >= 0 ? row[columnMap.analysis] : ''
          },
          creator: userId,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        };
        
        questions.push(question);
      } catch (error) {
        console.error(`第${i+1}行数据处理失败:`, error);
        failList.push({
          row: i + 1,
          error: error.message
        });
      }
    }
    
    // 5. 批量导入数据库
    const successList = [];
    
    if (questions.length > 0) {
      // 分批插入，每次最多插入100条
      const batchSize = 100;
      
      for (let i = 0; i < questions.length; i += batchSize) {
        const batch = questions.slice(i, i + batchSize);
        
        try {
          const importResult = await db.runTransaction(async transaction => {
            for (const question of batch) {
              await transaction.collection('questions').add({
                data: question
              });
            }
            return batch.length;
          });
          
          successList.push(...batch.map((_, index) => i + index + 1));
        } catch (error) {
          console.error(`批量导入第${i+1}到${i+batchSize}条数据失败:`, error);
          
          // 记录失败信息
          batch.forEach((_, index) => {
            failList.push({
              row: i + index + 1,
              error: '批量导入失败'
            });
          });
        }
      }
    }
    
    // 6. 删除临时文件
    await cloud.deleteFile({
      fileList: [fileID]
    });
    
    return {
      success: true,
      total: rows.length - 1,
      successCount: successList.length,
      failCount: failList.length,
      failList
    };
  } catch (error) {
    console.error('Excel导入失败:', error);
    return {
      success: false,
      message: '导入失败: ' + error.message
    };
  }
}; 